package com.school.config;


import com.school.common.intereceptor.UserInterceptor;
import jakarta.annotation.Resource;
import org.jetbrains.annotations.NotNull;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.servlet.config.annotation.AsyncSupportConfigurer;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * Spring MVC配置类
 * 配置异步任务执行器以支持异步请求处理
 */
@Configuration
@EnableAspectJAutoProxy(exposeProxy = true)
public class WebMvcConfig implements WebMvcConfigurer {
    @Resource
    private JwtUtils jwtUtils;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")  // 允许所有来源
                .allowedMethods("*")  // 允许所有方法
                .allowedHeaders("*"); // 允许所有头
        // 注意：使用通配符(*)时不能启用allowCredentials
    }
    @Override
    public void addInterceptors(@NotNull InterceptorRegistry registry) {
        registry.addInterceptor(new UserInterceptor(jwtUtils, stringRedisTemplate))
                .excludePathPatterns(
                        "/user/loginByUserName",
                        "/user/loginByPhone",
                        "/user/register",
                        "/doc.html",
                        "/webjars/**",
                        "/v3/api-docs/**",
                        "/swagger-ui.html"
                ).order(0);
    }

    @Override
    public void addResourceHandlers(@NotNull ResourceHandlerRegistry registry) {
        // 配置拦截器访问静态资源
        registry.addResourceHandler("doc.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/favicon.ico")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    /**
     * 配置异步请求的处理器
     */
    @Override
    public void configureAsyncSupport(@NotNull AsyncSupportConfigurer configurer) {
        // 设置异步任务执行器
        configurer.setTaskExecutor(mvcTaskExecutor());
        // 设置超时时间（单位：毫秒）
        configurer.setDefaultTimeout(300000); // 5分钟
    }

    /**
     * 创建用于MVC异步处理的任务执行器
     * 使用ThreadPoolTaskExecutor替代默认的SimpleAsyncTaskExecutor
     */
    @Bean
    public AsyncTaskExecutor mvcTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 核心线程数
        executor.setCorePoolSize(10);
        // 最大线程数
        executor.setMaxPoolSize(50);
        // 队列容量
        executor.setQueueCapacity(100);
        // 线程名前缀
        executor.setThreadNamePrefix("mvc-async-");
        // 线程池关闭前等待所有任务完成
        executor.setWaitForTasksToCompleteOnShutdown(true);
        // 等待终止的时间（秒）
        executor.setAwaitTerminationSeconds(60);
        executor.initialize();
        return executor;
    }
}
